////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.EntityClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.DaoClasses;
using RPSDAL.RelationClasses;
using RPSDAL.ValidatorClasses;
using RPSDAL.TypedViewClasses;
using RPSDAL.StoredProcedureCallerClasses;
using RPSDAL.HelperClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;

public partial class LetterTemplate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Parameters.LoggedUser != -1)
            {
                UserEntity eUser = new UserEntity(Parameters.LoggedUser);
                RoleEntity eRole = new RoleEntity(eUser.RoleId);

                if (!eRole.HasEditTemplate)
                {
                    Parameters.LoggedUser = -1;
                    Response.Redirect("Default.aspx");
                    return;
                }
            }


            btnAddTag.Attributes.Add("OnClick", "return AddTag(this)");
            lstTags.Attributes.Add("OnDblClick", "return AddTag(this)");
            LoadTags();

            imgLogo.Style["display"] = "none";
            ckRemoveLogo.Style["display"] = "none";

            if (Request.QueryString["id"] != null)
            {
                try
                {
                    if (Request.QueryString["sav"] != null && Request.QueryString["sav"]=="1")
                    {
                        lblSavedTemplate.Visible = true;
                    }

                    TemplateEntity eTemplate = new TemplateEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));

                    txtName.Text = eTemplate.Name;
                    txtLetterTemplate.Text = eTemplate.Template;

                    if (!String.IsNullOrEmpty(eTemplate.FilePath))
                    {
                        imgLogo.ImageUrl = eTemplate.FileUrl;
                        imgLogo.Style["display"] = "inline";
                        ckRemoveLogo.Style["display"] = "inline";
                    }

                }
                catch { }
            }
        }
    }

    #region user interface

    /// <summary>
    /// save template
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Save Template");
        TemplateEntity eTemplate = new TemplateEntity();
        if (IsPostBack && !String.IsNullOrEmpty(Request.QueryString["id"])) 
        {
            eTemplate = new TemplateEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));
        }

        int index = 0;
        if (eTemplate.IsNew || eTemplate.Name.ToUpper() != txtName.Text.ToUpper())
        {
            TemplateCollection cTemplates = new TemplateCollection();

            IPredicateExpression filter = new PredicateExpression();
            filter.Add(TemplateFields.Name == txtName.Text);
            index = cTemplates.GetDbCount(filter);
        }

        eTemplate.Name = txtName.Text;

        
        if (index == 0)
        {
            lblSteluta.Visible = false;
            lblTemplateExist.Visible = false;
        }
        else
        {
            lblSteluta.Visible = true;
            lblTemplateExist.Visible = true;
            return;
        }

        eTemplate.Template = txtLetterTemplate.Text;

        if (ckRemoveLogo.Checked) 
        {
            if (File.Exists(eTemplate.FilePath))
            {
                File.Delete(eTemplate.FilePath);
            }

            eTemplate.FilePath = "";
        }

        if (Request.Files.Count == 1 && Request.Files[0].FileName != "")
        {
            if (IsPostBack && File.Exists(eTemplate.FilePath))
            {
                File.Delete(eTemplate.FilePath);
            }

            eTemplate.FilePath = Methods.UploadFile(Request.Files[0],MapPath("UploadedFiles"));
            eTemplate.FileUrl = eTemplate.FilePath.Replace(MapPath("UploadedFiles") + "\\", PageName()+ "UploadedFiles/");
        }

        eTemplate.Save();

        Response.Redirect("Template.aspx?id=" + Global.EncryptString(eTemplate.TemplateId.ToString())+"&sav=1");
    }

    private string PageName()
    {
        string url = Request.Url.AbsoluteUri;
        string[] fragments = url.Split('/');
        return url.Replace(fragments[fragments.Length - 1], "");
    }

    /// <summary>
    /// Load Tags
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LoadTags()
    {
        SqlConnection conn = new SqlConnection(DbUtils.ActualConnectionString);
        DataTable schemaTable = new DataTable();
        conn.Open();
        lstTags.Items.Clear();

        SqlCommand cmd = new SqlCommand("select * from [vTemplate]", conn);
        try
        {
            SqlDataReader dataReader =  cmd.ExecuteReader();
            schemaTable = dataReader.GetSchemaTable();

            //For each field in the table...
            foreach (DataRow myField in schemaTable.Rows)
            {
                //For each property of the field...
                foreach (DataColumn myProperty in schemaTable.Columns)
                {
                    if (myProperty.ColumnName == "ColumnName")
                    {
                        lstTags.Items.Add("[" + myField[myProperty].ToString() + "]");
                    }
                }
            }

            lstTags.DataBind();
            dataReader.Close();
        }
        catch { }

        cmd = new SqlCommand("select Name from ContactPageField", conn);
        try
        {
            SqlDataReader dataReader = cmd.ExecuteReader();

           while (dataReader.Read())
            {
                lstTags.Items.Add("["+dataReader.GetValue(0)+"]");
            }

            dataReader.Close();
        }
        catch { }

        
        conn.Dispose();
    }

    /// <summary>
    /// cancel template creation
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect("TemplateList.aspx");
    }


    #endregion user interface





}
